<?php
/*
 * @Author: lokei
 * @Date: 2023-07-01 10:09:05
 * @LastEditors: lokei
 * @LastEditTime: 2023-07-02 21:47:34
 * @Description: 
 */

namespace App\Http\Controllers\Platform\Info;

use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;

use OpenApi\Annotations\Get;
use OpenApi\Annotations\MediaType;
use OpenApi\Annotations\Response;
use OpenApi\Annotations\Schema;
use App\Http\Responses\CommResp;

class OsController extends Controller
{
	/**
	 * @Get(
	 *     path="/api/platform/os/get",
	 *     tags={"【平台】平台管理"},
	 *     summary="操作系统信息",
	 *     @Response(
	 *         response="200",
	 *         description="正常操作响应",
	 *         @MediaType(
	 *             mediaType="application/json",
	 *             @Schema(
	 *                 allOf={
	 *                     @Schema(ref="#/components/schemas/CommResp")
	 *                 }
	 *             )
	 *         )
	 *     )
	 * )
	 *
	 * @param Request $request
	 *
	 * @return CommResp
	 */
	public function get()
	{
		$res = ResultTool::success();
		$ncpu = 1;
		if (is_file('/proc/cpuinfo')) {
			$cpuinfo = file_get_contents('/proc/cpuinfo');
			preg_match_all('/^processor/m', $cpuinfo, $matches);
			$ncpu = count($matches[0]);
		}
		$load = sys_getloadavg();
		$dd = 0;
		foreach ($load as $k => $v) {
			$dd += $v;
		}
		$load1 =  $load[0];
		$cpu_usage = $load1 * 100;

		$free = shell_exec('free');
		$free = (string)trim($free);
		$free_arr = explode("\n", $free);
		$mem = explode(" ", $free_arr[1]);
		$mem = array_filter($mem);
		$mem = array_merge($mem);
		$memory_usage = $mem[2] / $mem[1] * 100;

		$total = disk_total_space('.');
		$free = disk_free_space('.');

		$sum_kj = $this->readable_size($total);
		$sy_kj = $this->readable_size($free);

		$res['data'] = [
			'ncpu' => $ncpu,
			'cpu_usage' => $cpu_usage,
			'memory_total' => $this->readable_size($mem[1] * 1024),
			'memory_usage' => $memory_usage,
			'disk_total' => $sum_kj,
			'disk_usage' => (floatval($sy_kj) / floatval($sum_kj)) * 100
		];
		return $res;
	}

	function readable_size($length)
	{
		$units = array('B', 'kB', 'MB', 'GB', 'TB');
		foreach ($units as $unit) {
			if ($length > 1024)
				$length = round($length / 1024, 1);
			else
				break;
		}
		return $length . ' ' . $unit;
	}
}
